package com.hucii.app.view;

import java.util.Observable;
import java.util.Observer;

import com.hucii.app.MyApplication;
import com.hucii.app.service.RemotePictureManager;
import com.hucii.app.service.RemotePictureManager.Request;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 自定义ImageView(可网络获取图片,设置是否圆角)
 * 
 * 
 */
public class RemoteImageView extends ImageView {

	private class BroadcastReceiverWrapper {
		private Context ct = null;
		private boolean isRegisted = false;
		private IntentFilter filter = null;
		private BroadcastReceiver receiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				Bundle mData = intent.getBundleExtra(MSG_BUNDLE_NAME);
				if (mData.getString(MSG_IMAGE_URL).equals(mCurrentImageURL)) {
					if (mData.getBoolean(MSG_IMAGE_SUCCESS)) {
						Bitmap im = (Bitmap) mData.getParcelable(MSG_IMAGE_BITMAP);

						mSelf.setImageBitmap(im);
						mCurrentImageStatus = imageLoadingStatus.SUCCESS;
					} else {
						if (mDefaultImageId != -1)
							mSelf.setImageResource(mDefaultImageId);
						mCurrentImageStatus = imageLoadingStatus.FAILED;
					}
					unRegisterAction();
				}
			}

		};

		public BroadcastReceiverWrapper(Context c) {
			ct = c;
			this.registerAction();
		}

		public void registerAction() {
			if (!isRegisted) {
				if (filter == null) {
					filter = new IntentFilter();
					filter.addAction(mAction);
				}
				ct.registerReceiver(receiver, filter);
				this.isRegisted = true;
			}
		}

		public void unRegisterAction() {
			try {
				if (isRegisted && receiver != null) {
					ct.unregisterReceiver(receiver);
					this.isRegisted = false;
				}
			} catch (Exception e) {
			}

		}
	}

	private static String mAction = "com.soufun.org.agent.ImageRefresh";
	private RemoteImageView mSelf = null;
	private Context mContext = null;
	private String mCurrentImageURL = null;
	private imageLoadingStatus mCurrentImageStatus = imageLoadingStatus.NULL;
	private int mDefaultImageId = -1;
	private float mRoundPx = 6;
	private boolean mIsRounded = false;

	private static enum imageLoadingStatus {
		SUCCESS(1), FAILED(0), LOADING(2), NULL(-1);
		private int s;

		private imageLoadingStatus(int _s) {
			this.s = _s;
		}

		public int getStatus() {
			return this.s;
		}

		public static boolean isSuccess(int _s) {
			return (_s == SUCCESS.s) ? true : false;
		}

		public static boolean isLoading(int _s) {
			return (_s == LOADING.s) ? true : false;
		}
	}

	private static final String MSG_IMAGE_URL = "MSG_IMAGE_URL";
	private static final String MSG_IMAGE_BITMAP = "MSG_IMAGE_BITMAP";
	private static final String MSG_BUNDLE_NAME = "MSG_BUNDLE_NAME";
	private static final String MSG_IMAGE_SUCCESS = "MSG_IMAGE_SUCCESS";

	private static RemotePictureManager mRrm = null;
	private static RemoteResourceManagerObserver mRo = null;

	private static class RemoteResourceManagerObserver implements Observer {
		@Override
		public void update(Observable observable, Object data) {
			Request request = (Request) data;
			Bundle mData = new Bundle();
			mData.putString(MSG_IMAGE_URL, request.url);
			mData.putParcelable(MSG_IMAGE_BITMAP, request.image);
			mData.putBoolean(MSG_IMAGE_SUCCESS, request.success);
			Intent intent = new Intent();
			intent.setAction(mAction);
			intent.putExtra(MSG_BUNDLE_NAME, mData);
			MyApplication.getSelf().sendBroadcast(intent);
		}
	}

	private BroadcastReceiverWrapper mReceiver = null;

	private Bitmap getPicture(String url) {
		return mRrm.getPicture(url);
	}

	/**
	 * 设置是否为圆角图片
	 * 
	 * @param isRounded
	 */
	public void setIsRounded(boolean isRounded) {
		this.mIsRounded = isRounded;
	}

	/**
	 * 设置图片
	 * 
	 * @param url
	 *            图片url地址
	 * @param defaultImage
	 *            默认图片
	 * @param roundPx
	 *            圆角系数(需大于0,默认为6)
	 */
	public void setImage(String url, int defaultImage, float roundPx) {
		if (url.startsWith("http://")) {
			if ((mCurrentImageURL != null && url.contentEquals(mCurrentImageURL))
					&& (imageLoadingStatus.isSuccess(mCurrentImageStatus.getStatus()) || imageLoadingStatus.isLoading(mCurrentImageStatus.getStatus()))) {
				return;
			}

			mCurrentImageURL = url;
			if (mReceiver == null) {
				mReceiver = new BroadcastReceiverWrapper(mContext);
			} else {
				mReceiver.registerAction();
			}
			if (defaultImage != -1)
				mDefaultImageId = defaultImage;
			if (roundPx > 0)
				mRoundPx = roundPx;
			Bitmap im = getPicture(url);
			if (im != null) {
				// if (mIsRounded) {
				// im = ImageUtils.getRoundedCornerBitmap(im, mRoundPx);
				// }
				this.setImageBitmap(im);
				mCurrentImageStatus = imageLoadingStatus.SUCCESS;
				mReceiver.unRegisterAction();
			} else {
				if (mDefaultImageId != -1)
					this.setImageResource(mDefaultImageId);
				mCurrentImageStatus = imageLoadingStatus.LOADING;
			}
		}
	}

	/**
	 * 设置图片
	 * 
	 * @param url
	 *            图片url地址
	 * @param defaultImage
	 *            默认图片
	 */
	public void setImage(String url, int defaultImage) {
		setImage(url, defaultImage, mRoundPx);
	}

	/**
	 * 设置图片
	 * 
	 * @param url
	 *            图片url地址
	 */
	public void setImage(String url) {
		setImage(url, mDefaultImageId, mRoundPx);
	}

	static {
		mRrm = MyApplication.getSelf().getRPM();
		mRo = new RemoteResourceManagerObserver();
		mRrm.addObserver(mRo);
	}

	public RemoteImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		mSelf = this;
	}

}
